import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score

    # 聚类分类
class ClusterUtils(object):
        def __init__(self):
            self.df = pd.read_csv('scenic_data.csv')
        
        def get_k(self):
            '''
            获取合适的k值
            '''
            # 提取特征并标准化
            features = self.df[['non_weekend_ratio', 'eldery_ratio', 'out_province_ratio']]
            scaler = StandardScaler()
            scaled_features = scaler.fit_transform(features)
            # 计算不同k值下的轮廓系数
            silhouette_scores = []
            for k in range(2, 11):
                kmeans = KMeans(n_clusters=k, random_state=42)
                cluster_labels = kmeans.fit_predict(scaled_features)
                silhouette_avg = silhouette_score(scaled_features, cluster_labels)
                silhouette_scores.append(silhouette_avg)
            # 绘制轮廓系数图
            plt.plot(range(2, 11), silhouette_scores, marker='o')
            plt.title('Silhouette Method for Optimal k')
            plt.xlabel('Number of Clusters (k)')
            plt.ylabel('Silhouette Score')
            plt.show()
if __name__ == '__main__':
        cu = ClusterUtils()
        cu.get_k()
